#region LicenseHeader

// Copyright 2012 The Trustees of Indiana University.  All rights reserved.
// 
// The Indiana University licenses this file to you under the Apache License, 
// Version 2.0 (the "License"); you may not use this file except in compliance 
// with the License.  You may obtain a copy of the License at 
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software 
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
// See the License for the specific language governing permissions and 
// limitations under the License.
// 
// @author Thilina Gunarathne (tgunarat@indiana.edu)

#endregion

#region

using System.Text;

#endregion

namespace NAligner.Formats
{
    /// <summary>
    ///   <a href="http://www.ncbi.nlm.nih.gov/BLAST/fasta.html">FASTA</a> formatter
    /// </summary>
    public class FASTA : AlignmentFormatter
    {
        /// <summary>
        ///   Number of characters per line
        /// </summary>
        private const int LINE_WIDTH = 60;

        /// <summary>
        ///   Constructor for FASTA.
        /// </summary>
        public FASTA()
        {
            Id = "FASTA";
        }

        /// <summary>
        ///   Returns the name, description and sequence combined in one string. The length of each line in the sequence is FASTA.LINE_LENGTH
        /// </summary>
        public virtual string Format(Sequence sequence)
        {
            StringBuilder buffer = new StringBuilder(">");
            buffer.Append(sequence.Label == null ? "" : sequence.Label);
            buffer.Append("\n");

            for (int i = 0, n = sequence.Length; i*LINE_WIDTH < n; i++)
            {
                for (int j = i*LINE_WIDTH, m = (i + 1)*LINE_WIDTH < n ? (i + 1)*LINE_WIDTH : n; j < m; j++)
                {
                    buffer.Append(sequence.Subsequence(j, 1));
                }
                buffer.Append("\n");
            }
            return buffer.ToString();
        }

        /// <returns> FASTA format of the input alignment </returns>
        public override string Format(PairwiseAlignment alignment)
        {
            StringBuilder buffer = new StringBuilder();
            StringBuilder s1 = new StringBuilder();
            StringBuilder s2 = new StringBuilder();
            s1.Append(alignment.Sequence1);
            s2.Append(alignment.Sequence2);
            buffer.Append(Format(new Sequence(s1.ToString(), alignment.Name1, "", SequenceType.Protein)));
            buffer.Append(Format(new Sequence(s2.ToString(), alignment.Name2, "", SequenceType.Protein)));
            return buffer.ToString();
        }
    }
}